package code.springboot.sharding.service;

import code.springboot.sharding.dataobject.OrderDO;
import code.springboot.sharding.mapper.OrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class OrderService {

    @Resource
    private OrderMapper orderMapper;

    /**
     * 往从库发起一次订单查询.在 Sharding-JDBC 的读写分离策略里,默认读取从库.
     * 往主库发起一次订单写入.写入，肯定是操作主库的。
     * 往主库发起一次订单查询.在 Sharding-JDBC 中,
     * 读写分离约定:同一线程且同一数据库连接内,如有写入操作,
     * 以后的读操作均从主库读取,用于保证数据一致性.
     */
    @Transactional
    public void add(OrderDO order) {
        // 这里先假模假样的读取一下。读取从库
        OrderDO exists = orderMapper.selectById(1);
        System.out.println(exists);

        // 插入订单
        orderMapper.insert(order);

        // 这里先假模假样的读取一下。读取主库
        exists = orderMapper.selectById(1);
        System.out.println(exists);
    }

    public OrderDO findById(Integer id) {
        return orderMapper.selectById(id);
    }
}
